<template>
  <div class="aside-right_bottom" ref="bottom" id="aside-right_bottom">
    <ul class="set-tool">
      <li class="set-tool_list" id="tool-list" @click="fetchArticleLabel()">
        文章标签<i></i>
        <div class="tag-box" v-show="showBar">
          <ul>
            <li class="list"
                :key="item.articleLabelId"
                :class="{'select-platform':selectedLabelID==item.articleLabelId}"
                v-for="(item, index) in articleLabes"
                @click.stop="selectLable(item.articleLabelId)">{{item.articleLabelName}}
            </li>
          </ul>
        </div>
      </li>
      <li class="set-tool_list" @click="setCover()">设置封面<i></i></li>
      <li class="select-tool set-tool_list" id="platform-list" @click="selectTool">
        平台选择<i></i>
        <div class="selector-box" v-show="showSelectTool&&stateArr.length>0">
          <p class="title">默认发布到V房，请选择三方平台：</p>
          <span class="img-box" v-for="(item,index) in stateArr" v-if="stateArr" :key="index">
						<img src="../../assets/images/duigou.png" class="icon-img" :class="{'selected': item.published}"/>
            <!--<img :src="require(`../../assets/images/${item.id}.png`)" @click.stop="lightIcon($event,item)"
                 class="platform-img" :class="{'gray': !item.selected&&!item.published}"/>-->

            <!--灰度兼容-->
            <svg>
						    <image :xlink:href="require(`../../assets/images/${item.id}.png`)" @click.stop="lightIcon($event,item)"
                       class="platform-img" :class="{'gray': !item.selected&&!item.published}" width="50"
                       height="50"></image>
						</svg>
					</span>
        </div>

        <div class="selector-box" v-show="showSelectTool&&stateArr.length==0">
          <div class="nodata-box">
            <p class="nodata-title">默认发布到V房，您也可以</p>
            <p class="nodata-title">在“<span @click.stop="gotoRelease">发布管理</span>”授权更多平台</p>
          </div>
        </div>


      </li>
      <li class="publishing set-tool_list" @click="goPublish">{{publishing ? "发布中..." : "一键发布"}}</li>
    </ul>
    <ul class="tool-btn">
      <li class="save-btn-two" @click="saveArticle()">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-save"></use>
        </svg>
        保存
      </li>
      <li @click="handleshowPreview(true)">效果预览</li>
    </ul>

    <!--lyd新增-已发布平台弹层-->
    <div class="platform-modal" v-show="showWXLayer"></div>
    <div class="platform-layer" v-show="showWXLayer">
      <svg class="icon" aria-hidden="true" @click.stop="closeWXLayer">
        <use xlink:href="#icon-close"></use>
      </svg>
      <div class="title"><span>已成功发布的平台</span></div>
      <ul>
        <li>
          <img src="../../assets/images/icon80-vf.png"/>
          <p>V房号</p>
        </li>
        <li v-if="publishedPlatforList.indexOf(2)>-1">
          <img src="../../assets/images/icon80-xb.png"/>
          <p>新浪微博</p>
        </li>
        <li v-if="publishedPlatforList.indexOf(3)>-1">
          <img src="../../assets/images/icon80-tt.png"/>
          <p>今日头条</p>
        </li>
      </ul>
      <div class="tips">
        <p>由于您的公众号未完成企业认证，暂时无法一键发布到微信</p>
        <a href="https://mp.weixin.qq.com/" target="_blank"><p class="tips-link">>>点此快速发布到微信公众号<<</p></a>
      </div>
    </div>
    <!--灰度兼容 勿刪-->
    <svg style="width:0; height: 0;">
      <filter id="grayscale">
        <feColorMatrix type="matrix"
                       values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"/>
      </filter>
    </svg>

  </div>

</template>

<script>
  import {mapState, mapActions} from 'vuex';
  import util from '@/lib/util';

  export default {
    name: 'AsideRightBottom',
    data() {
      return {
        stateArr: [],//展示的平台对象列表（维护平台信息和选中状态）
        showSelectTool: false,
        showBar: false,
        articleLabes: [],//文章标签列表
        selectedLabelID: 0,//选择的文章标签ID
        selectPlatformArr: [],//选择要发布的平台id列表
        saveParams: {},
        publishedPlatforList: [],//已经发布成功的平台id列表
        showWXLayer: false,//一键发布微信失败引导弹层
        publishing: false//是否正在发布
      }
    },
    created() {
    },
    mounted: function () {
      const that = this;
      document.getElementById('app').addEventListener('click', function (ev) {
        var ev = ev || window.event;
        var target = ev.target || ev.srcElement;
        if (target.id != 'tool-list') {
          that.showBar = false;
        }
        if (target.id != 'platform-list') {
          that.showSelectTool = false;
        }

        if (target.id != 'showSetting') {
          let box = document.querySelector('.tag-box');

          box.style.display = 'none';
        }

        try {
          if (!target.getAttribute('data-class')) {
            let aLi = document.querySelectorAll('.tag-art-list');
            for (let i = 0; i < aLi.length; i++) {
              aLi[i].classList.remove('selectIcon')
            }
          }
        } catch (e) {
        }
      }, false);
    },
    computed: {
      ...mapState([
        'articleLabelId',
        'folderId',
        'articleDetail',//当前文章对象
        'showChooseImg',
        'previewInfo'
      ]),
    },
    watch: {

      articleDetail(curVal, oldVal) {
        //切换新的文章之后初始化状态
        if (curVal.articleId !== oldVal.articleId) {
          this._initState();
        }
      }


    },
    methods: {
      ...mapActions([
        'handleshowPreviewLayer',
        'handleShowsetCover',
        'handleisFromAddImg',
        'updateArticlelist',
        'fetchArticleDetail'
      ]),
      _initState() {
        this.selectedLabelID = 0;
        this.saveParams = {};
        this.selectPlatformArr = [];
        (this.stateArr || []).forEach((item, index) => {
          if (!item.published) {
            item.selected = false;
          }
        });
      },
      handleshowPreview() {
        this.handleshowPreviewLayer(true);
        //预览界面 自适应 屏幕大小 预览前先保存文章,随后再预览的时候调用
        this.saveArticle(null, false);
        this.$nextTick(function () {
          let previewlayer = document.getElementById("previewlayer");
          let previewModal = document.getElementById("previewModal");
          let height1 = previewlayer.clientHeight;
          let height2 = previewModal.clientHeight;
          let num = (height1 - 40) / 950;
          previewModal.style.transformOrigin = ("center", "top")
          previewModal.style.transform = "scale(" + num + ")";

        })
      },
      setCover() {
        // 初始化展示裁剪功能
        this.handleisFromAddImg(false);
        // 设置封面展示素材库
        this.handleShowsetCover(true);
      },
      //加载文章标签列表
      fetchArticleLabel() {
        this.showBar = !this.showBar;

        let that = this;
        util.ajax.get(`/articleLabel/list`).then((res) => {
          if (res.code == 1) {
            that.articleLabes = res.data;
            if (that.articleDetail.articleLabelId && that.selectedLabelID == 0) {
              that.selectedLabelID = that.articleDetail.articleLabelId;
            }
          }
        });

      },
      //选择标签事件
      selectLable(labelId) {
        this.selectedLabelID = labelId;
        this.saveParams["articleLabelId"] = labelId;
        this.showBar = !this.showBar;
      },
      //设置发布平台的状态
      lightIcon(e, item) {
        if (item["published"]) {
          return;
        }
        //对选择做toggle
        item["selected"] = !item["selected"];
        //将选择的平台放在已选择平台数组selectPlatformArr中
        let itemIndex = this.selectPlatformArr.indexOf(item["id"]);
        //先去掉此平台
        if (itemIndex > -1) {
          this.selectPlatformArr.splice(itemIndex, 1);
        }
        //如果是已经选中则再加入进来
        if (item["selected"]) {
          this.selectPlatformArr.push(item["id"]);

        }
      },
      modal() {
        //弹窗 one  two  three 三种
        this.$confirm('内容', '标题', {
          confirmButtonText: '确定',
          customClass: 'self-modal-one',
          showCancelButton: false,
          showClose: false
        })
      },

      openCenter() {
        //弹窗  one  two  three 三种
        this.$message({
          message: '居中的文字',
          type: '',
          center: true,
          customClass: 'self-tips-three'
        });
      },
      //保存文章
      saveArticle(callback, showtip) {
        let that = this, imgArr = [];
        let paramsValue = {
          'id': this.articleDetail.articleId,
          'origContent': (this.previewInfo.textContent || '').replace(/\r\n/g, "").replace(/\n/g, ""),
          //对保存的文章中不是同一个来自自己图库中的图片要过滤掉
          'content': (this.previewInfo.editorHtml || '').replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
            if (capture.indexOf("dav-images.oss-cn-qingdao.aliyuncs.com/") == -1) {
              return "";
            } else {
              imgArr.push(capture);
              return match;
            }
          }),
          'title': this.previewInfo.title
        };

        if(that.selectedLabelID>0){
          paramsValue["articleLabelId"]=that.selectedLabelID;
          that.articleLabes.forEach((item,index)=>{
            if(item.articleLabelId==that.selectedLabelID){
              paramsValue["articleLabelName"]=item.articleLabelName;
              return;
            }
          });
        }
        //把文章中的图片单独提出来提交上去
        paramsValue["images"] = imgArr.join(",");

        if (!paramsValue.title && !paramsValue.content) {
          this.$message.error("请填写文章标题或正文");
          return;
        }

        paramsValue = Object.assign({}, paramsValue, this.saveParams);

        util.ajax.post(`/article/update`, {...paramsValue}).then((res) => {
          if (res.code == 1) {

            this.updateArticlelist(res.data);
            if (typeof showtip === "undefined") {
              this.$message({
                message: '保存成功',
                type: '',
                center: true,
                customClass: 'self-tips-three',
              });
            }
            this.fetchArticleDetail({id: that.articleDetail.articleId}).then((res2) => {
              if (typeof callback === "function") {
                callback();
              }
            });

          } else {
            if (typeof showtip === "undefined") {
              this.$message.error(res.msg);
            }
          }
        });
      },
      //一键发布
      goPublish() {

        //正在发布中则禁止连续发布
        if (this.publishing) {
          return;
        }

        let _that = this;

        this.saveArticle(function () {
          if (_that.publishing) {
            return;
          }
          //发布过的文章只要有更新内容，在v房平台可以一直发，
          // 第三方平台只能发一次by tiansx

          if (_that.selectPlatformArr.length === 0 && _that.articleDetail.isPublish) {
            _that.$message.error("请选择预发布的平台");
            return;
          }

          if (!_that.articleDetail.articleLabelId) {
            _that.$message.error("请选择文章标签");
            return;
          }

          let params = {
            'articleId': _that.articleDetail.articleId,
            'platformTypeList': _that.selectPlatformArr
          };

          _that.publishing = true;
          util.ajax.post('/article/publish', params).then((res) => {
            if (res.code == 1) {
              //判断平台发布结果resultList
              //选择了发布到微信平台，则需要查看微信平台的发布结果
              let list = res.data.resultList || [];
              _that.publishedPlatforList = res.data.publishedList || [];
              let errPlatform = [];
              list.forEach((item, index) => {
                //微信平台，如果errcode=1025则表示公众号没有完成微信认证
                if (item.platform === 1 && item.errCode === 1025) {
                  _that.showWXLayer = true;
                } else if (item.errCode !== 1) {
                  errPlatform.push(res.data.platformList[0][item.platform] + "发布失败,原因：" + item.errMsg);
                }
              });
              if (!_that.showWXLayer) {
                if (errPlatform.length > 0) {
                  _that.$message.error(errPlatform.join("<br/>"));
                } else {
                  _that.$message({
                    message: '一键发布成功',
                    type: '',
                    center: true,
                    customClass: 'self-tips-three',
                  });
                }
              }
              //清空选择的平台
              _that.selectPlatformArr = [];
              _that.stateArr = [];
              _that.publishing = false;//恢复进行中状态
            } else {

              _that.$message.error(res.msg);
              _that.selectPlatformArr = [];
              _that.stateArr = [];
              _that.publishing = false;//恢复进行中状态
            }
          });
        }, false);
      },

      //平台选择处理函数
      selectTool() {
        this.showSelectTool = !this.showSelectTool;
        let that = this;
        if (this.showSelectTool) {
          let params = {'id': this.articleDetail.articleId};
          if (this.articleDetail.articleId) {
            util.ajax.post('/article/getAuthList', params).then((res) => {
              if (res.code == 1) {
                //判断是否已经选中
                let getItemSelectState = function (platformid) {
                  let selected = false;
                  that.stateArr.forEach((item, index) => {
                    if (item.id == platformid) {

                      selected = item.selected;
                      return;
                    }
                  });
                  return selected;
                };
                //逻辑：将已经授权的平台列表展示出来，将已经发布的点亮打钩，待发布的置灰，这次选择的点亮
                //已经授权的平台列表
                let authList = res.data.authList;
                //已经发布成功的平台
                let publishedList = res.data.publishedList;
                //所有平台列表
                let platformList = res.data.platformList;

                if (platformList.length > 0) {
                  let platform = platformList[0];
                  //将所有授权的列表找出来
                  let tempStateArr = [];
                  for (let i = 0; i < authList.length; i++) {
                    if (platform[authList[i]]) {
                      tempStateArr.push({
                        'id': authList[i],
                        'name': platform[authList[i]],
                        'published': publishedList.indexOf(authList[i]) > -1,
                        'selected': getItemSelectState(authList[i])
                      });
                    }
                  }
                  this.stateArr = tempStateArr;
                }
              }
            });
          }
        }

      },


      gotoRelease() {
        this.$router.push({path: "/Release/ReleaseManage"});
      },
      closeWXLayer() {
        this.showWXLayer = false;
      }

    }
  }
</script>

<style lang="scss" scoped>
  @import "@/assets/css/style.scss";

  .select-platform {
    background: $mainborderColor;
    color: $colorWhite !important;
  }

  .aside-right_bottom {
    position: absolute;
    left: 0px;
    bottom: 0px;
    right: 0px;
    z-index: 9;
    border-top: 1px solid $listborderColor;
    background: #f8f8f8;
    .set-tool {
      padding: 0px 40px;
      float: left;
      .set-tool_list {
        position: relative;
        margin-right: 17px;
        display: inline-block;
        width: 80px;
        line-height: 58px;
        cursor: pointer;
        .tag-box {
          position: absolute;
          bottom: 50px;
          left: -30px;
          z-index: 10;
          text-align: center;
          width: 128px;
          /*height: 164px;*/
          background: #fff;
          font-size: $fs16;
          border: 1px solid $listborderColor;
          border-radius: 10px;
          color: $vfConcentColor;
          &:after,
          &:before {
            border: solid transparent;
            content: ' ';
            height: 0;
            top: 100%;
            position: absolute;
            width: 0;
          }
          &:after {
            border-width: 6px;
            border-top-color: #fff;
            left: 60px;
          }
          &:before {
            border-width: 8px;
            border-top-color: $listborderColor;
            left: 58px;
          }
          ul {
            /*height: 164px;*/
            border-radius: 10px;
            overflow-x: hidden;
            overflow-y: auto;
            .list {
              line-height: 40px;
              color: $vfConcentColor;
              font-size: $fs14;
              border-bottom: 1px solid $listborderColor;
              &:last-child{
              	border-bottom: 0px solid $listborderColor;
              }
            }
          }
        }
        .selector-box {
          position: absolute;
          top: -105px;
          left: -95px;
          z-index: 9;
          text-align: center;
          width: 260px;
          height: 110px;
          background: #fff;
          font-size: $fs16;
          border: 1px solid $listborderColor;
          border-radius: 10px;
          color: $vfConcentColor;
          &:after,
          &:before {
            border: solid transparent;
            content: ' ';
            height: 0;
            top: 100%;
            position: absolute;
            width: 0;
          }
          &:after {
            border-width: 6px;
            border-top-color: #fff;
            left: 124px;
          }
          &:before {
            border-width: 8px;
            border-top-color: $listborderColor;
            left: 122px;
          }
          .title {
            margin: 15px 0px 10px;
            text-align: center;
            line-height: 20px;
            font-size: $fs12;
          }
          .nodata-box {
            padding-top: 31px;
            .nodata-title {
              font-size: $fs16;
              line-height: 24px;
              color: $vfConcentColor;
              span {
                width: auto;
                height: auto;
                color: #fd942f;
              }
            }
          }

          span {
            position: relative;
            margin: 0px 17px 0px 0px;
            display: inline-block;
            width: 50px;
            height: 50px;
            background-repeat: no-repeat;
            &:last-child {
              margin: 0px;
            }
            .icon-img {
              position: absolute;
              bottom: -5px;
              right: -5px;
              z-index: 99;
              display: none;
            }
            .selected {
              display: block !important;
            }
            svg {
              width: 100%;
              height: 100%;
            }
            .platform-img {
              width: 100%;
              height: 100%;
            }
            .select {
              display: block;
            }
          }
          .nogray {
            opacity: 1 !important;
            -webkit-filter: grayscale(0) !important;
            -moz-filter: grayscale(0) !important;
            -ms-filter: grayscale(0) !important;
            -o-filter: grayscale(0) !important;
            filter: grayscale(0) !important;
            filter: gray;
          }
          .gray {
            opacity: .5;
            -webkit-filter: grayscale(100%);
            -moz-filter: grayscale(100%);
            -ms-filter: grayscale(100%);
            -o-filter: grayscale(100%);
            filter: grayscale(100%);
            filter: gray;
            filter: url(#grayscale);
          }
          .img-last {
            margin-right: 0px;
          }
        }
        i {
          &:after {
            content: '';
            display: inline-flex;
            margin: 20px 0px 0px 5px;
            width: 0;
            height: 0;
            border-left: 5px solid transparent;
            border-right: 5px solid transparent;
            border-top: 6px solid $listborderColor;
          }
        }
      }
      .publishing {
        width: 100px;
        text-align: center;
        line-height: 30px;
        border: 1px solid $listborderColor;
        border-radius: 20px;
        background: $colorWhite;
        cursor: pointer;
      }
    }
    .tool-btn {
      padding: 9px 10px;
      float: right;
      li {
        float: right;
        margin-right: 10px;
        width: 120px;
        line-height: 40px;
        font-size: $fs16;
        text-align: center;
        color: $listTitleColor;
        border: 1px solid $listborderColor;
        border-radius: 20px;
        background: $colorWhite;
        cursor: pointer;
        .icon {
          position: relative;
          top: 1px;
          width: 20px;
          height: 20px;
        }
      }
      .save-btn-two {
        background: $mainborderColor;
        border: 1px solid $mainborderColor;
        color: $colorWhite;
      }
    }

    .platform-modal {
      position: fixed;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      background: #000000;
      opacity: .8;
    }
    .platform-layer {
      position: fixed;
      top: 50%;
      left: 50%;
      margin-top: -239px;
      margin-left: -350px;
      width: 700px;
      height: 478px;
      border-radius: 8px;
      background: #fff;
      text-align: center;
      .icon {
        position: absolute;
        right: 20px;
        top: 20px;
        width: 30px;
        height: 30px;
        color: #989898;
      }
      .title {
        margin: 58px 0px 78px;
        display: inline-block;
        width: 560px;
        text-align: center;
        font-size: $fs16;
        color: #565656;
        border-top: 1px solid #e6e6e6;
        text-align: center;
        span {
          padding: 0px 10px;
          background: #fff;
          position: relative;
          top: -11px;
        }
      }
      ul {
        margin-bottom: 80px;
        display: inline-block;
        li {
          margin: 0px 30px;
          float: left;
          img {
            margin-bottom: 5px;
            width: 80px;
            height: 80px;
            border-radius: 50%;
          }
          p {
            text-align: center;
            font-size: $fs14;
            line-height: 20px;
            color: #565656;
          }
        }
      }
      .tips {
        margin-bottom: 80px;
        p {
          font-size: $fs16;
          line-height: 20px;
          color: #565656;
        }
        .tips-link {
          margin-top: 20px;
          color: $mainfontColor;
          cursor: pointer;
        }
      }
    }
  }
</style>
